package ru.tulupov.helloandroid;

import java.util.Calendar;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {
	private EditText firstName;
	private EditText lastName;
	private DatePicker birthdate;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		firstName = (EditText) findViewById(R.id.main_first_name);
		lastName = (EditText) findViewById(R.id.main_last_name);
		birthdate = (DatePicker) findViewById(R.id.main_birthdate);
		final Button next = (Button) findViewById(R.id.main_next);

		next.setOnClickListener(new View.OnClickListener() {

			public void onClick(View view) {
				Intent intent = new Intent(MainActivity.this,
						InfoActivity.class);
				try {
					intent.putExtra(InfoActivity.FIRST_NAME, getFirstName());
					intent.putExtra(InfoActivity.LAST_NAME, getLastName());
					intent.putExtra(InfoActivity.AGE, getAge());

					startActivity(intent);
				} catch (IllegalArgumentException e) {
					Toast.makeText(MainActivity.this, e.getMessage(),
							Toast.LENGTH_SHORT).show();
				}
			}
		});

	}

	/**
	 * @throws IllegalArgumentException
	 * @return
	 */
	private CharSequence getFirstName() {
		CharSequence s = firstName.getText();
		if (s.length() == 0) {
			throw new IllegalArgumentException(
					getString(R.string.main_invalid_first_name));
		}
		return s;
	}

	/**
	 * @throws IllegalArgumentException
	 * @return
	 */
	private CharSequence getLastName() {
		CharSequence s = lastName.getText();
		if (s.length() == 0) {
			throw new IllegalArgumentException(
					getString(R.string.main_invalid_last_name));
		}
		return s;
	}

	/**
	 * @throws IllegalArgumentException
	 * @return
	 */
	private int getAge() {
		int currentYear = Calendar.getInstance().get(Calendar.YEAR);
		int age = currentYear - birthdate.getYear();
		if (age < 0) {
			throw new IllegalArgumentException(
					getString(R.string.main_invalid_birthdate));
		}
		return age;
	}

}
